package com.cyz.controller;

import com.cyz.dao.UserDao;
import com.cyz.entity.User;
import com.cyz.service.UserService;
import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.*;

@RestController
@RequestMapping("/generate")
@Slf4j
public class GenerateDataController {

    @Autowired
    private UserService service;

    @GetMapping("/test")
    public void generateDate() throws InterruptedException {

        int numberOfThreads = 1000;
        int total = 900000;

        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        CountDownLatch latch = new CountDownLatch(total);
        List<User> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < total; i++){
            executorService.execute(()->{
                Faker faker = new Faker(Locale.CHINA);
                String name = faker.name().fullName();
                String city = faker.address().city();
                String tel = faker.phoneNumber().cellPhone();

                User user = new User(name, city, tel);
                list.add(user);
                latch.countDown();
            });
        }

        latch.await();
        service.insertBatch(list);
    }

    @GetMapping("/info/{result}")
    public String getInfo(@PathVariable String result){
        if (result.contains("info")){
            log.info(result);
        }else {
            log.error(result);
        }
        return "info";
    }
}
